$(function () {
    //初始化绑定默认的属性
    $.upLoadDefaults = $.upLoadDefaults || {};
    $.upLoadDefaults.property = {
        multiple: false, //是否多文件
        water: false, //是否加水印
        thumbnail: false, //是否生成缩略图
        sendurl: null, //发送地址
        filetypes: "jpg,jpge,png,gif", //文件类型
        filesize: "2048", //文件大小
        btntext: "浏览...", //上传按钮的文字
        swf: null //SWF上传控件相对地址
    };
    //初始化上传控件
    $.fn.InitUploader = function (p) {
        var smallimage = function () {
            var x = 22;
            var y = 20;

            $(".uploadsmallimage").hover(function (e) {
                var imgfix = "";
                if ($(this).width() > $(this).height()) {
                    imgfix = 'width="200"';
                } else {
                    imgfix = 'height="200"';
                }
                $("body").append('<p id="bigimage" style="position:absolute; display:none;z-index:3;"><img src="' + $(this).val() + '" ' + imgfix + ' alt="无图，请不要自行改文本框里的内容，或重新上传" style="padding:5px; background:#fff; border:1px solid #e3e3e3;" /></p>');
                $(this).find('img').stop().fadeTo('slow', 0.5);
                widthJudge(e);
                $("#bigimage").fadeIn('fast');
            }, function () {
                $(this).find('img').stop().fadeTo('slow', 1);
                $("#bigimage").remove();
            });

            $(".uploadsmallimage").mousemove(function (e) {
                widthJudge(e);
            });

            function widthJudge(e) {
                var marginRight = document.documentElement.clientWidth - e.pageX;
                var imageWidth = $("#bigimage").width();
                if (marginRight < imageWidth) {
                    x = imageWidth + 22;
                    $("#bigimage").css({ top: (e.pageY - y) + 'px', left: (e.pageX - x) + 'px' });
                } else {
                    x = 22;
                    $("#bigimage").css({ top: (e.pageY - y) + 'px', left: (e.pageX + x) + 'px' });
                };
            }
        };
        var fun = function (parentObj) {
            p = $.extend({}, $.upLoadDefaults.property, p || {});
            var btn_id = "btn-" + Math.floor(Math.random() * 100000000);
            var btnObj = $('<div class="upload-btn" id="' + btn_id + '">' + p.btntext + '</div>').appendTo(parentObj);
            //初始化属性
            p.sendurl += "?action=UpLoadFile";
            if (p.water) {
                p.sendurl += "&IsWater=1";
            }
            if (p.thumbnail) {
                p.sendurl += "&IsThumbnail=1";
            }
            if (!p.multiple) {
                p.sendurl += "&DelFilePath=" + parentObj.siblings(".upload-path").val();
            }
            var multi_selection = false;
            p.multiple ? multi_selection = true : "";

            var uploader = new plupload.Uploader({
                //创建实例的构造方法
                runtimes: 'html5,flash,silverlight,html4', //上传插件初始化选用那种方式的优先级顺序
                browse_button: btn_id, // 上传按钮
                url: p.sendurl, //远程上传地址
                flash_swf_url: '/scripts/plupload/Moxie.swf', //flash文件地址
                silverlight_xap_url: '/scripts/plupload/Moxie.xap', //silverlight文件地址
                chunk_size: '100kb',
                filters: {
                    max_file_size: '6gb', //最大上传文件大小（格式100b, 10kb, 10mb, 1gb）
                    mime_types: [//允许文件上传类型jpg,png,gif,zip,doc
                        { title: "files", extensions: (p.filetypes ? p.filetypes : "*") }
                    ]
                },
                multipart_params: {
                    DelFilePath: parentObj.siblings(".upload-path").val()
                },
                multi_selection: multi_selection, //true:ctrl多文件上传, false 单文件上传
                init: {
                    FilesAdded: function (up, files) { //文件上传前
                        //如果是单文件上传，把旧的文件地址传过去
                        if (!p.multiple) {
                            uploader.setOption("multipart_params", { DelFilePath: parentObj.siblings(".upload-path").val() })
                            //uploader.multipart_params["DelFilePath"] = parentObj.siblings(".upload-path").val();
                        }
                        //防止重复创建
                        if (parentObj.children(".upload-progress").length == 0) {
                            //创建进度条
                            var fileProgressObj = $('<div class="upload-progress"></div>').appendTo(parentObj);
                            var progressText = $('<span class="txt">正在上传，请稍候...</span>').appendTo(fileProgressObj);
                            var progressBar = $('<span class="bar"><b></b></span>').appendTo(fileProgressObj);
                            var progressCancel = $('<a class="close" title="取消上传">关闭</a>').appendTo(fileProgressObj);
                            var progressTips = $('<span class="tips">22.21M / 78.77M</span>').appendTo(fileProgressObj);

                            //绑定点击事件
                            progressCancel.click(function () {
                                //uploader.destroy();
                                uploader.stop();
                                uploader.removeFile(files[0]);
                                //uploader.splice(0, 1);
                                fileProgressObj.remove();
                            });
                        }
                        uploader.start();
                        //if ($("#ul_pics").children("li").length > 30) {
                        //    alert("您上传的图片太多了！");
                        //    uploader.destroy();
                        //} else {
                        //    var li = '';
                        //    plupload.each(files, function (file) { //遍历文件
                        //        li += "<li id='" + file['id'] + "'><div class='progress'><span class='bar'></span><span class='percent'>0%</span></div></li>";
                        //    });
                        //    $("#ul_pics").append(li);
                        //    uploader.start();
                        //}
                    },
                    UploadProgress: function (up, file) { //上传中，显示进度条
                        var percent = file.percent;
                        var progressObj = parentObj.children(".upload-progress");
                        progressObj.children(".txt").html(file.name);
                        progressObj.find(".bar b").width(percent + "%");
                        progressObj.find(".tips").html(FileSizeChange(file.loaded) + " / " + FileSizeChange(file.size));

                        //$("#" + file.id).find('.bar').css({ "width": percent + "%" });
                        //$("#" + file.id).find(".percent").text(percent + "%");
                    },
                    FileUploaded: function (up, file, info) { //文件上传成功的时候触发
                        var data = JSON.parse(info.response);
                        if (data.status == '0') {
                            var progressObj = parentObj.children(".upload-progress");
                            progressObj.children(".txt").html(data.msg);
                        }
                        if (data.status == '1') {
                            //如果是单文件上传，则赋值相应的表单
                            if (!p.multiple) {
                                parentObj.siblings(".upload-name").val(data.name);
                                parentObj.siblings(".upload-path").val(data.path);
                                parentObj.siblings(".upload-size").val(data.size);
                            } else {
                                addImage(parentObj, data.path, data.thumb);
                            }
                            var progressObj = parentObj.children(".upload-progress");
                            progressObj.children(".txt").html("上传成功：" + file.name);
                            progressObj.remove();
                            //缩略图
                            var ext = file.name.substring(file.name.lastIndexOf('.')+1).toLowerCase()
                            if ("jpg,gif,png,jpeg".indexOf(ext) > -1) {
                                parentObj.siblings(".upload-path").addClass("uploadsmallimage");
                                smallimage();
                            } else {
                                parentObj.siblings(".upload-path").removeClass("uploadsmallimage");
                                parentObj.siblings(".upload-path").unbind();
                            }
                        }
                        uploader.removeFile(file); //从队列中移除

                        //$("#" + file.id).html("<div class='img'><img src='" + data.path + "'/></div><p>" + data.name + "</p>");
                        //$("#" + file.id).html("<div class='img'><img src='" + info.response + "'/></div><p>" + info.response + "</p>");
                    },
                    Error: function (up, err) { //上传出错的时候触发
                        if (err.response) {
                            var data = JSON.parse(err.response);
                            alert(data.msg);
                        } else {
                            alert(err.message);
                        }
                        var progressObj = parentObj.children(".upload-progress");
                        progressObj.remove();
                    }
                }
            });
            uploader.init();

            ////初始化WebUploader
            //var uploader = WebUploader.create({
            //    auto: true, //自动上传
            //    swf: p.swf, //SWF路径
            //    server: p.sendurl, //上传地址
            //    pick: {
            //        id: btnObj,
            //        multiple: p.multiple
            //    },
            //    accept: {
            //        /*title: 'Images',*/
            //        extensions: p.filetypes
            //        /*mimeTypes: 'image/*'*/
            //    },
            //    formData: {
            //        'DelFilePath': '' //定义参数
            //    },
            //    fileVal: 'Filedata', //上传域的名称
            //    fileSingleSizeLimit: p.filesize * 1024,//文件大小
            //    compress: null
            //});

            ////当validate不通过时，会以派送错误事件的形式通知
            //uploader.on('error', function (type) {
            //    switch (type) {
            //        case 'Q_EXCEED_NUM_LIMIT':
            //            alert("错误：上传文件数量过多！");
            //            break;
            //        case 'Q_EXCEED_SIZE_LIMIT':
            //            alert("错误：文件总大小超出限制！");
            //            break;
            //        case 'F_EXCEED_SIZE':
            //            alert("错误：文件大小超出限制！");
            //            break;
            //        case 'Q_TYPE_DENIED':
            //            alert("错误：禁止上传该类型文件！");
            //            break;
            //        case 'F_DUPLICATE':
            //            alert("错误：请勿重复上传该文件！");
            //            break;
            //        default:
            //            alert('错误代码：' + type);
            //            break;
            //    }
            //});

            ////当有文件添加进来的时候
            //uploader.on('fileQueued', function (file) {
            //    //如果是单文件上传，把旧的文件地址传过去
            //    if (!p.multiple) {
            //        uploader.options.formData.DelFilePath = parentObj.siblings(".upload-path").val();
            //    }
            //    //防止重复创建
            //    if (parentObj.children(".upload-progress").length == 0) {
            //        //创建进度条
            //        var fileProgressObj = $('<div class="upload-progress"></div>').appendTo(parentObj);
            //        var progressText = $('<span class="txt">正在上传，请稍候...</span>').appendTo(fileProgressObj);
            //        var progressBar = $('<span class="bar"><b></b></span>').appendTo(fileProgressObj);
            //        var progressCancel = $('<a class="close" title="取消上传">关闭</a>').appendTo(fileProgressObj);
            //        //绑定点击事件
            //        progressCancel.click(function () {
            //            uploader.cancelFile(file);
            //            fileProgressObj.remove();
            //        });
            //    }
            //});

            ////文件上传过程中创建进度条实时显示
            //uploader.on('uploadProgress', function (file, percentage) {
            //    var progressObj = parentObj.children(".upload-progress");
            //    progressObj.children(".txt").html(file.name);
            //    progressObj.find(".bar b").width(percentage * 100 + "%");
            //});

            ////当文件上传出错时触发
            //uploader.on('uploadError', function (file, reason) {
            //    uploader.removeFile(file); //从队列中移除
            //    alert(file.name + "上传失败，错误代码：" + reason);
            //});

            ////当文件上传成功时触发
            //uploader.on('uploadSuccess', function (file, data) {
            //    if (data.status == '0') {
            //        var progressObj = parentObj.children(".upload-progress");
            //        progressObj.children(".txt").html(data.msg);
            //    }
            //    if (data.status == '1') {
            //        //如果是单文件上传，则赋值相应的表单
            //        if (!p.multiple) {
            //            parentObj.siblings(".upload-name").val(data.name);
            //            parentObj.siblings(".upload-path").val(data.path);
            //            parentObj.siblings(".upload-size").val(data.size);
            //        } else {
            //            addImage(parentObj, data.path, data.thumb);
            //        }
            //        var progressObj = parentObj.children(".upload-progress");
            //        progressObj.children(".txt").html("上传成功：" + file.name);
            //    }
            //    uploader.removeFile(file); //从队列中移除
            //});

            ////不管成功或者失败，文件上传完成时触发
            //uploader.on('uploadComplete', function (file) {
            //    var progressObj = parentObj.children(".upload-progress");
            //    progressObj.children(".txt").html("上传完成");
            //    //如果队列为空，则移除进度条
            //    if (uploader.getStats().queueNum == 0) {
            //        progressObj.remove();
            //    }
            //});
        };
        return $(this).each(function () {
            fun($(this));
        });

    };
    /*
    *  文件大小转换
    */
    function FileSizeChange(FactSize) {
        var m_strSize = 0;
        if (FactSize < 1024.00)
            m_strSize = FactSize.toFixed(2) + "Byte";
        else if (FactSize >= 1024.00 && FactSize < 1048576)
            m_strSize = (FactSize / 1024.00).toFixed(2) + "K";
        else if (FactSize >= 1048576 && FactSize < 1073741824)
            m_strSize = (FactSize / 1024.00 / 1024.00).toFixed(2) + "M";
        else if (FactSize >= 1073741824)
            m_strSize = (FactSize / 1024.00 / 1024.00 / 1024.00).toFixed(2) + "G";
        return m_strSize;
    }
});

/*图片相册处理事件
======================*/
//添加图片相册
function addImage(targetObj, originalSrc, thumbSrc) {
    //插入到相册UL里面
    var newLi = $('<li>'
    + '<input type="hidden" name="hid_photo_name" value="0|' + originalSrc + '|' + thumbSrc + '" />'
    + '<input type="hidden" name="hid_photo_remark" value="" />'
    + '<input type="hidden" name="hid_photo_sort_id" value="99" />'
    + '<div class="img-box" onclick="setFocusImg(this);">'
    + '<img src="' + thumbSrc + '" bigsrc="' + originalSrc + '" />'
    + '<span class="remark"><i>暂无描述...</i></span>'
    + '</div>'
    + '<a href="javascript:;" onclick="setRemark(this);">描述</a>'
    + '<a href="javascript:;" onclick="setSort(this);">排序</a>'
    + '<a href="javascript:;" onclick="delImg(this);">删除</a>'
    + '</li>');
    newLi.appendTo(targetObj.siblings(".photo-list").children("ul"));

    //默认第一个为相册封面
    var focusPhotoObj = targetObj.siblings(".focus-photo");
    if (focusPhotoObj.val() == "") {
        focusPhotoObj.val(thumbSrc);
        newLi.children(".img-box").addClass("selected");
    }
}
//设置相册封面
function setFocusImg(obj) {
    var focusPhotoObj = $(obj).parents(".photo-list").siblings(".focus-photo");
    focusPhotoObj.val($(obj).children("img").eq(0).attr("src"));
    $(obj).parent().siblings().children(".img-box").removeClass("selected");
    $(obj).addClass("selected");
}
//设置排序
function setSort(obj) {
    var parentObj = $(obj); //父对象
    var hidSortObj = parentObj.prevAll("input[name='hid_photo_sort_id']").eq(0); //取得隐藏值
    var d = parent.dialog({
        title: "图片排序",
        padding:'10',
        content: '排序：<input id="ImageSort" style="font-size:12px;padding:3px;color:#000;border:1px #d2d2d2 solid;vertical-align:middle;width:100px;height:22px;" value="' + hidSortObj.val() + '"/>  只能输入数字',
        button: [{
            value: '确认',
            callback: function () {
                var sortObj = $('#ImageSort', parent.document);
                if (sortObj.val()=="") {
                    parent.dialog({
                        title: '提示',
                        content: '亲，您总该写个数字进去吧？',
                        okValue: '确定',
                        ok: function () { },
                        onclose: function () {
                            sortObj.focus();
                        }
                    }).showModal();
                    return false;
                }
                hidSortObj.val(sortObj.val());
            },
            autofocus:true
        }]
    }).showModal();
}
//设置图片描述
function setRemark(obj) {
    var parentObj = $(obj); //父对象
    var hidRemarkObj = parentObj.prevAll("input[name='hid_photo_remark']").eq(0); //取得隐藏值
    var d = parent.dialog({
        title: "图片描述",
        content: '<textarea id="ImageRemark" style="margin:10px 0;font-size:12px;padding:3px;color:#000;border:1px #d2d2d2 solid;vertical-align:middle;width:300px;height:50px;">' + hidRemarkObj.val() + '</textarea>',
        button: [{
            value: '批量描述',
            callback: function () {
                var remarkObj = $('#ImageRemark', parent.document);
                if (remarkObj.val() == "") {
                    parent.dialog({
                        title: '提示',
                        content: '亲，总该写点什么吧？',
                        okValue: '确定',
                        ok: function () { },
                        onclose: function () {
                            remarkObj.focus();
                        }
                    }).showModal();
                    return false;
                }
                parentObj.parent().parent().find("li input[name='hid_photo_remark']").val(remarkObj.val());
                parentObj.parent().parent().find("li .img-box .remark i").html(remarkObj.val());
            }
        }, {
            value: '单张描述',
            callback: function () {
                var remarkObj = $('#ImageRemark', parent.document);
                if (remarkObj.val() == "") {
                    parent.dialog({
                        title: '提示',
                        content: '亲，总该写点什么吧？',
                        okValue: '确定',
                        ok: function () { },
                        onclose: function () {
                            remarkObj.focus();
                        }
                    }).showModal();
                    return false;
                }
                hidRemarkObj.val(remarkObj.val());
                parentObj.siblings(".img-box").children(".remark").children("i").html(remarkObj.val());
            },
            autofocus: true
        }]
    }).showModal();
}
//删除图片LI节点
function delImg(obj) {
    var parentObj = $(obj).parent().parent();
    var focusPhotoObj = parentObj.parent().siblings(".focus-photo");
    var smallImg = $(obj).siblings(".img-box").children("img").attr("src");
    $(obj).parent().remove(); //删除的LI节点
    //检查是否为封面
    if (focusPhotoObj.val() == smallImg) {
        focusPhotoObj.val("");
        var firtImgBox = parentObj.find("li .img-box").eq(0); //取第一张做为封面
        firtImgBox.addClass("selected");
        focusPhotoObj.val(firtImgBox.children("img").attr("src")); //重新给封面的隐藏域赋值
    }
}

